import math
import torch
from torch import nn
from d2l import torch as d2l


# 当查询和键是不同长度的矢量时，可以使用加性注意力作为评分函数

def masked_softmax(X, valid_lens):
    """通过在最后一个轴上掩蔽元素来执行softmax操作"""
    # X:3D张量，valid_lens:1D或2D张量
    if valid_lens is None:
        return nn.functional.softmax(X, dim=-1)
    else:
        shape = X.shape
        if valid_lens.dim() == 1:
            valid_lens = torch.repeat_interleave(valid_lens, shape[1])
        else:
            valid_lens = valid_lens.reshape(-1)
        # 最后一轴上被掩蔽的元素使用一个非常大的负值替换，从而其softmax输出为0
        X = d2l.sequence_mask(X.reshape(-1, shape[-1]), valid_lens,
                              value=-1e6)
        return nn.functional.softmax(X.reshape(shape), dim=-1)


# @save
class DotProductAttention(nn.Module):
    """缩放点积注意力"""

    def __init__(self, dropout, **kwargs):
        super(DotProductAttention, self).__init__(**kwargs)
        self.dropout = nn.Dropout(dropout)

    # queries的形状：(batch_size，查询的个数，d)
    # keys的形状：(batch_size，“键－值”对的个数，d)
    # values的形状：(batch_size，“键－值”对的个数，值的维度)
    # valid_lens的形状:(batch_size，)或者(batch_size，查询的个数)
    def forward(self, queries, keys, values, valid_lens=None):
        d = queries.shape[-1]
        # 设置transpose_b=True为了交换keys的最后两个维度
        # print(queries.shape, keys.shape)
        scores = torch.bmm(queries, keys.transpose(1, 2)) / math.sqrt(d)
        # print("scores",scores,valid_lens)
        # print(queries.shape,keys.shape,scores.shape,"运算")
        self.attention_weights = masked_softmax(scores, valid_lens)
        return torch.bmm(self.dropout(self.attention_weights), values)



# batch_size = 32
# queries, keys = torch.normal(0, 1, (batch_size, 7, 12)), torch.ones((batch_size, 13, 12))
# # values的小批量，两个值矩阵是相同的                               self.attention_weights
# values = torch.arange(156, dtype=torch.float32).reshape(1, 13, 12).repeat(
#     batch_size, 1, 1)
# valid_lens = torch.tensor([[i for i in range(1,8)]] * batch_size)
# attention = DotProductAttention(dropout=0.5)
# attention.eval()
# attention(queries, keys, values, valid_lens)
# print("Q ", queries.shape)
# print("K ", keys.shape)
# print("V ", values.shape)
# print("valid_lens",valid_lens)
# print(attention(queries, keys, values, valid_lens).shape)

batch_size = 5
queries, keys = torch.normal(0, 1, (batch_size, 7, 12)), torch.ones((batch_size, 7, 12))
# values的小批量，两个值矩阵是相同的                               self.attention_weights
values = torch.arange(84, dtype=torch.float32).reshape(1, 7, 12).repeat(
    batch_size, 1, 1)
valid_lens = torch.tensor([[i for i in range(1,8)]] * batch_size)
attention = DotProductAttention(dropout=0.5)
attention.eval()
attention(queries, keys, values, valid_lens)
print("Q ", queries.shape)
print("K ", keys.shape)
print("V ", values.shape)
print("valid_lens",valid_lens)
print(attention(queries, keys, values, valid_lens).shape)
